import {
  Button,
  Card,
  Form,
  Input,
  message,
  Modal,
  Table,
  Tooltip,
} from "antd";
import type { ColumnsType } from "antd/lib/table";
import React, { Key } from "react";
import {
  reqGetHospitalSetList,
  reqRemoveHospital,
  reqBatchRemoveHospitalList,
} from "@/api/hospital/hospitalSet";

import {
  SearchOutlined,
  FormOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import "./hospialSet.css";
import { useState, useEffect } from "react";
import {
  HospitalSetList,
  HospitalSetItem,
} from "@api/hospital/model/hospitalSetTypes";
import { useNavigate } from "react-router-dom";

export default function HospitalSet() {
  const [current, setCurrent] = useState(1); //当前页
  const [total, setTotal] = useState(0); //总条数
  const [pageSize, setPageSize] = useState(4); // 每页显示条数
  const [dataSource, setDataSource] = useState<HospitalSetList>([]); // 数据源
  const [finish, setFinish] = useState(false); //请求完成状态

  // 创建form 对象  管理表单数据
  const [form] = Form.useForm();

  // 管理弹窗的显示状态
  const [model, setModel] = useState(false);

  // 保存当前数据id
  const [id, setId] = useState("");

  // 管理所有选中医院id 的数组
  const [selectedIds, setSelectedIds] = useState<Key[]>([]);

  // 查询提交 获取数据
  const onFinish = () => {
    getHospitalList();
  };
  // 清空搜索框 并刷新数据
  const onReset = () => {
    getHospitalList();
  };

  // 创建编程式导航
  let navigate = useNavigate();

  // 异步获取医院列表
  const getHospitalList = async function () {
    setFinish(true);
    let { hoscode, hosname } = form.getFieldsValue();
    let res = await reqGetHospitalSetList({
      page: current,
      limit: pageSize,
      hoscode,
      hosname,
    });

    setDataSource(res.records); // 设置数据源
    setTotal(res.total); // 设置总数量
    setFinish(false); //关闭菊花图
    // console.log(res);
  };

  // 跳转到修改医院页面并带id
  const goUpdateHispital = function (row: any) {
    return () => {
      navigate(`/syt/hospital/hospitalSet/edit/${row.id}`);
    };
  };

  // 删除医院数据
  let removeHospital = (id: number) => {
    return async () => {
      if (id) {
        // 单个删除
        // console.log(1);
        await reqRemoveHospital(id);
        message.success("删除成功");
        setId("");
        setModel(false);
        await getHospitalList(); // 删除完后更新数据
      } else if (selectedIds) {
        //批量删除
        // console.log(2);
        await reqBatchRemoveHospitalList(selectedIds);
        setModel(false);
        message.success("删除成功");
        await getHospitalList(); // 删除完后更新数据
      }
    };
  };

  // 批量删除
  const batchRemoveHospitalList = async () => {
    setModel(true);
  };

  useEffect(() => {
    getHospitalList();
  }, [current, pageSize]);

  const columns: ColumnsType<any> = [
    {
      title: "序号",
      render: (value: any, row: any, index: number) => {
        return index + 1;
      },
      align: "center",
      width: "80px",
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
      align: "center",
    },
    {
      title: "医院编号",
      dataIndex: "hoscode",
      align: "center",
    },
    {
      title: "api基础路径",
      dataIndex: "apiUrl",
      align: "center",
    },
    {
      title: "签名",
      dataIndex: "signKey",
    },
    {
      title: "联系人姓名",
      dataIndex: "contactsName",
      align: "center",
    },
    {
      title: "操作",
      width: "150px",

      render: (value: any, row: any, index: number) => {
        return (
          <>
            <Tooltip placement="bottom" title="修改医院">
              <Button
                icon={<FormOutlined />}
                className="mr"
                type="primary"
                onClick={goUpdateHispital(row)}
              ></Button>
            </Tooltip>

            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              onClick={() => {
                setModel(true);
                setId(row.id);
              }}
            ></Button>
          </>
        );
      },
      fixed: "right",
      align: "center",
    },
  ];
  return (
    <Card>
      {/* 搜索框 */}
      <Form
        onReset={onReset}
        layout="inline"
        name="basic"
        autoComplete="off"
        form={form}
        onFinish={onFinish}
      >
        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>

        <Form.Item name="hoscode">
          <Input placeholder="医院编号" />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
            查询
          </Button>
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="default" htmlType="reset">
            清除
          </Button>
        </Form.Item>
      </Form>
      {/* 添加和批量删除 */}
      <div className="mt">
        <Button
          type="primary"
          htmlType="reset"
          className="mr"
          onClick={() => {
            navigate("add");
          }}
        >
          添加
        </Button>
        <Button
          type="default"
          htmlType="reset"
          disabled={selectedIds.length === 0}
          onClick={batchRemoveHospitalList}
        >
          批量删除
        </Button>
      </div>
      {/* 表格 */}
      <Table
        rowSelection={{
          type: "checkbox",
          onChange: (
            selectedRowKeys: Key[], // 获取所有被选中的 id
            selectedRows: HospitalSetItem[] //获取所有被选中的 医院信息
          ) => {
            // 把获取到的id 数组 保存
            setSelectedIds(selectedRowKeys);
          },
        }}
        loading={finish}
        bordered
        columns={columns}
        dataSource={dataSource}
        className="mt"
        rowKey="id"
        pagination={{
          pageSize: pageSize,
          current: current, // 当前页码
          total: total, //总数,
          showQuickJumper: true, //是否快速跳转至某页
          showSizeChanger: true, //是否展示 pageSize 切换器，当 total 大于 50 时默认为 true
          pageSizeOptions: [4, 6, 8, 10], //指定每页可以显示多少条
          showTotal: (total) => {
            //用于显示数据总量和当前数据顺序
            return <span>当前总数是:{total} 条</span>;
          },
          onChange: (page, limit) => {
            //   console.log(page, limit);
            setCurrent(page);
            setPageSize(limit);
          },
        }}
        scroll={{ x: "1400px" }}
      ></Table>

      {/* 确认删除弹窗 */}
      <Modal
        className="center"
        title="删除"
        visible={model} //是否显示
        onCancel={() => {
          // 点击取消按钮
          setModel(false);
          // 清空保存id
          setId("");
          setSelectedIds([]);
        }}
        onOk={removeHospital(+id)}
      >
        <h2>你确定要删除医院数据吗？</h2>
      </Modal>
    </Card>
  );
}
